package com.example.elysiumease.handler;

import org.apache.ibatis.type.BaseTypeHandler;
import org.apache.ibatis.type.JdbcType;
import org.apache.ibatis.type.TypeHandler;
import org.locationtech.jts.geom.Geometry;
import org.locationtech.jts.io.WKTWriter;

import java.sql.CallableStatement;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class WKTConverter extends BaseTypeHandler<Geometry> implements TypeHandler<Geometry> {

    @Override
    public void setNonNullParameter(PreparedStatement ps, int i, Geometry parameter, JdbcType jdbcType) throws SQLException {
        WKTWriter wktWriter = new WKTWriter();
        String wkt = wktWriter.write(parameter);
        ps.setString(i, wkt);
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, String columnName) throws SQLException {
        String wkt = rs.getString(columnName);
        return parseWKT(wkt);
    }

    @Override
    public Geometry getNullableResult(ResultSet rs, int columnIndex) throws SQLException {
        String wkt = rs.getString(columnIndex);
        return parseWKT(wkt);
    }

    @Override
    public Geometry getNullableResult(CallableStatement cs, int columnIndex) throws SQLException {
        String wkt = cs.getString(columnIndex);
        return parseWKT(wkt);
    }

    private Geometry parseWKT(String wkt) {
        if (wkt == null) {
            return null;
        }
        // 使用 WKTReader 将 WKT 字符串转换为 Geometry 对象
        try {
            return new org.locationtech.jts.io.WKTReader().read(wkt);
        } catch (Exception e) {
            throw new IllegalArgumentException("Invalid WKT format: " + wkt, e);
        }
    }
}